package com.tianyang.yukuaifu.business.login.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.jakewharton.rxbinding.view.RxView;
import com.tianyang.yukuaifu.R;
import com.tianyang.yukuaifu.base.BaseEditActivity;
import com.tianyang.yukuaifu.business.login.contract.LoginContract;
import com.tianyang.yukuaifu.business.login.presenter.LoginPresenter;
import com.tianyang.yukuaifu.business.login.provider.LoginOpenProvider;
import com.tianyang.yukuaifu.business.main.provider.MainOpenProvider;
import com.tianyang.yukuaifu.common.bean.TabEntity;
import com.tianyang.yukuaifu.common.interfaces.UrlConstants;
import com.tianyang.yukuaifu.module.immersionbar.ImmersionBar;
import com.tianyang.yukuaifu.module.roundview.RoundFrameLayout;
import com.tianyang.yukuaifu.module.roundview.RoundRelativeLayout;
import com.tianyang.yukuaifu.module.specialunit.OnClickableSpanListener;
import com.tianyang.yukuaifu.module.specialunit.SimplifySpanBuild;
import com.tianyang.yukuaifu.module.specialunit.unit.SpecialClickableUnit;
import com.tianyang.yukuaifu.module.tablelayout.CommonTabLayout;
import com.tianyang.yukuaifu.module.tablelayout.CustomTabEntity;
import com.tianyang.yukuaifu.module.tablelayout.listener.OnTabSelectListener;
import com.tianyang.yukuaifu.module.widget.EditTextWithDel;
import com.tianyang.yukuaifu.utils.SoftInputUtil;
import com.tianyang.yukuaifu.utils.ToastUtil;
import com.tianyang.yukuaifu.utils.VerifyUtil;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Description：登陆页
 */
public class LoginActivity extends BaseEditActivity implements LoginContract.View {

    @BindView(R.id.tabLayout)
    CommonTabLayout vTabLayout;
    @BindView(R.id.phoneNumberEt)
    EditTextWithDel phoneNumberEt;
    @BindView(R.id.pswRfl)
    RoundFrameLayout pswRfl;
    @BindView(R.id.pswEt)
    EditTextWithDel pswEt;
    @BindView(R.id.smsCodeRfl)
    RoundRelativeLayout smsCodeRfl;
    @BindView(R.id.smsCodeEt)
    EditTextWithDel smsCodeEt;
    @BindView(R.id.sendCodeTv)
    TextView sendCodeTv;
    @BindView(R.id.forgetTv)
    TextView forgetTv;
    @BindView(R.id.legal)
    TextView vLegal;
    @BindView(R.id.chooseIv)
    ImageView chooseIv;

    private LoginContract.Presenter mPresenter;

    private boolean isCheckAgree = false, isSmsLogin = true;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        super.initView();
        SpecialClickableUnit clickableUnit = new SpecialClickableUnit(new OnClickableSpanListener() {
            @Override
            public void onClick(TextView tv, String clickText) {
                MainOpenProvider.getInstance().openBrowserX5Activity(mContext, "《隐私政策》", UrlConstants.PRIVACY_POLICY);
            }
        });
        clickableUnit.setSpecialText("《隐私政策》");
        clickableUnit.setNormalTextColor(ContextCompat.getColor(mContext, R.color.color_base));
        clickableUnit.setPressTextColor(ContextCompat.getColor(mContext, R.color.base_press_color));

//        SpecialClickableUnit clickableUnit2 = new SpecialClickableUnit(new OnClickableSpanListener() {
//            @Override
//            public void onClick(TextView tv, String clickText) {
//                MainOpenProvider.getInstance().openBrowserX5Activity(mContext, "服务商合规展业规范", UrlConstants.AGREEMENT);
//            }
//        });
//        clickableUnit2.setSpecialText("《服务商合规展业规范》");
//        clickableUnit2.setNormalTextColor(ContextCompat.getColor(mContext, R.color.color_base));
//        clickableUnit2.setPressTextColor(ContextCompat.getColor(mContext, R.color.base_press_color));

        SimplifySpanBuild build = new SimplifySpanBuild(this, vLegal, "已充分阅读并遵守");
        build.appendSpecialUnit(clickableUnit);
//        build.appendSpecialUnit(clickableUnit2);
        build.appendNormalText("确保您的个人的权益得到保护。");
        vLegal.setText(build.build());
        mPresenter = new LoginPresenter(this);
    }

    @Override
    protected void initData() {
        super.initData();
        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        mTabEntities.add(new TabEntity("验证码登录", 0, 0));
        mTabEntities.add(new TabEntity("账号登录", 0, 0));
        vTabLayout.setTabData(mTabEntities);
        vTabLayout.setCurrentTab(0);
    }

    @Override
    protected void setListener() {
        super.setListener();
        RxView.clicks(sendCodeTv).throttleFirst(3, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (!isRespondEvent() || !checkParameterForSms()) return;
                        mPresenter.sendCode(String.valueOf(phoneNumberEt.getText()));
                    }
                });
        vTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 0) {
                    isSmsLogin = true;
                    pswRfl.setVisibility(View.GONE);
                    smsCodeRfl.setVisibility(View.VISIBLE);
                    forgetTv.setVisibility(View.INVISIBLE);
                } else {
                    isSmsLogin = false;
                    pswRfl.setVisibility(View.VISIBLE);
                    smsCodeRfl.setVisibility(View.GONE);
                    forgetTv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
    }

    @OnClick({R.id.loginBtn, R.id.registerTv, R.id.chooseIv, R.id.forgetTv})
    public void onClick(View view) {
        if (!isRespondEvent()) return;
        switch (view.getId()) {
            case R.id.loginBtn:
                if (checkParameter()) {
                    String userName = String.valueOf(phoneNumberEt.getText());
                    if (isSmsLogin) {
                        String smsCode = String.valueOf(smsCodeEt.getText());
                        mPresenter.smsLogin(userName, smsCode);
                    } else {
                        String password = String.valueOf(pswEt.getText());
                        mPresenter.login(userName, password);
                    }
                }
                break;
            case R.id.registerTv:
                LoginOpenProvider.getInstance().openRegisterActivity(mContext);
                break;
            case R.id.forgetTv:
                LoginOpenProvider.getInstance().openForgotLoginPwdActivity(mContext);
                break;
            case R.id.chooseIv:
                if (isCheckAgree) {
                    isCheckAgree = false;
                    chooseIv.setImageResource(R.drawable.ic_choose_normal);
                } else {
                    isCheckAgree = true;
                    chooseIv.setImageResource(R.drawable.ic_choose_checked);
                }
                break;
        }
    }

    @Override
    public void changeByStatus(boolean status) {
        if (status) {
            sendCodeTv.setEnabled(false);
            sendCodeTv.setTextColor(
                    ContextCompat.getColor(mContext, R.color.c_999999));
        } else {
            sendCodeTv.setText("获取验证码");
            sendCodeTv.setEnabled(true);
            sendCodeTv.setTextColor(
                    ContextCompat.getColor(mContext, R.color.color_base));
        }
    }

    @Override
    public void byoyomi(Long aLong) {
        sendCodeTv.setText(aLong + "秒");
    }

    private boolean checkParameterForSms() {
        Editable phoneNumber = phoneNumberEt.getText();
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastUtil.showTextViewPromptShort("手机号码不能为空");
            SoftInputUtil.openKeybord(phoneNumberEt, mContext);
            return false;
        } else if (VerifyUtil.checkPhoneNumber(phoneNumber)) {
            ToastUtil.showTextViewPromptShort("电话号码输入不正确");
            SoftInputUtil.openKeybord(phoneNumberEt, mContext);
            return false;
        }
        return true;
    }

    /**
     * 校验输入框
     */
    private boolean checkParameter() {
        String userName = String.valueOf(phoneNumberEt.getText());
        String password = String.valueOf(pswEt.getText());
        String code = String.valueOf(smsCodeEt.getText());
        if (TextUtils.isEmpty(userName)) {
            ToastUtil.showTextViewPromptShort("登录账号不能为空");
            SoftInputUtil.openKeybord(phoneNumberEt, mContext);
            return false;
        } else if (VerifyUtil.checkPhoneNumber(userName)) {
            ToastUtil.showTextViewPromptShort("登录账号输入不正确");
            SoftInputUtil.openKeybord(phoneNumberEt, mContext);
            return false;
        }
        if (isSmsLogin) {
            if (TextUtils.isEmpty(code)) {
                ToastUtil.showTextViewPromptShort("验证码不能为空");
                SoftInputUtil.openKeybord(smsCodeEt, mContext);
                return false;
            }
        } else {
            if (TextUtils.isEmpty(password)) {
                ToastUtil.showTextViewPromptShort("密码不能为空");
                SoftInputUtil.openKeybord(pswEt, mContext);
                return false;
            }
            if (password.length() < 6) {
                ToastUtil.showTextViewPrompt("密码不能小于6位数");
                SoftInputUtil.openKeybord(pswEt, mContext);
                return false;
            }
        }
        if (!isCheckAgree) {
            ToastUtil.show("请阅读并勾选《隐私政策》及《服务商合规展业规范》");
            SoftInputUtil.hideSoftInput(this);
            return false;
        }
        return true;
    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return mContext;
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    protected boolean hasCommonTitle() {
        return false;
    }

    @Override
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColorTransformEnable(true)
                .init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
